package org.diffshop.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.diffshop.common.constant.ProductConstant;
import org.diffshop.common.utils.PageUtils;
import org.diffshop.common.utils.Query;
import org.diffshop.product.dao.CategoryDao;
import org.diffshop.product.dao.PmsAttrAttrgroupRelationDao;
import org.diffshop.product.dao.PmsAttrDao;
import org.diffshop.product.dao.PmsAttrGroupDao;
import org.diffshop.product.entity.PmsAttrAttrgroupRelationEntity;
import org.diffshop.product.entity.PmsAttrEntity;
import org.diffshop.product.service.CategoryService;
import org.diffshop.product.service.PmsAttrService;
import org.diffshop.product.vo.AttrRespVO;
import org.diffshop.product.vo.AttrVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("pmsAttrService")
public class PmsAttrServiceImpl extends ServiceImpl<PmsAttrDao, PmsAttrEntity> implements PmsAttrService {
    @Autowired
    private PmsAttrAttrgroupRelationDao attrAttrgroupRelationDao;
    @Autowired
    private CategoryDao categoryDao;
    @Autowired
    private PmsAttrGroupDao attrGroupDao;
    @Autowired
    private CategoryService categoryService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PmsAttrEntity> page = this.page(
                new Query<PmsAttrEntity>().getPage(params),
                new QueryWrapper<PmsAttrEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 保存
     *
     * @param attrVO
     */
    @Transactional
    @Override
    public void saveAttr(AttrVO attrVO) {
        // 保存属性
        PmsAttrEntity attrEntity = new PmsAttrEntity();
        BeanUtils.copyProperties(attrVO, attrEntity);
        baseMapper.insert(attrEntity);

        if (attrVO.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_SALE.getCode()) {
            // 保存属性和属性分组的关系
            PmsAttrAttrgroupRelationEntity relationEntity = new PmsAttrAttrgroupRelationEntity();
            relationEntity.setAttrId(attrEntity.getAttrId());
            relationEntity.setAttrGroupId(attrVO.getAttrGroupId());

            attrAttrgroupRelationDao.insert(relationEntity);
        }
    }

    /**
     * 查询分类关联的属性
     *
     * @param params
     * @param type
     * @param catId
     * @return
     */
    @Override
    public PageUtils getAttrsByCatId(Map<String, Object> params, String type, Long catId) {
        LambdaQueryWrapper<PmsAttrEntity> queryWrapper = new LambdaQueryWrapper<>();

        String key = (String) params.get("key");
        if (StringUtils.isNotEmpty(key)) {
            queryWrapper.eq(PmsAttrEntity::getAttrId, key).or().like(PmsAttrEntity::getAttrName, key);
        }
        // ctId=0查询所有
        if (!catId.equals(0L)) {
            queryWrapper.eq(PmsAttrEntity::getCatelogId, catId);
        }
        queryWrapper.eq(
                PmsAttrEntity::getAttrType, ProductConstant.AttrEnum.ATTR_TYPE_SALE.getMsg().equals(type) ?
                        ProductConstant.AttrEnum.ATTR_TYPE_SALE.getCode() :
                        ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode());

        IPage<PmsAttrEntity> page = this.page(new Query<PmsAttrEntity>().getPage(params), queryWrapper);

        // 查询属性的所属分组和所属分类并封装到视图对象中
        List<AttrRespVO> respVOList = page.getRecords().stream().map(attrEntity -> {
            AttrRespVO attrRespVO = new AttrRespVO();
            BeanUtils.copyProperties(attrEntity, attrRespVO);
            String catelogName = categoryDao.selectNameById(attrEntity.getCatelogId());
            attrRespVO.setCatelogName(catelogName);
            if (ProductConstant.AttrEnum.ATTR_TYPE_BASE.getMsg().equals(type)) {
                Long groupId = attrAttrgroupRelationDao.selectGroupIdByAttrId(attrEntity.getAttrId());
                String groupName = attrGroupDao.selectNameById(groupId);
                attrRespVO.setGroupName(groupName);
            }
            return attrRespVO;
        }).collect(Collectors.toList());

        IPage<AttrRespVO> attrVOIPage = new Page<>();
        BeanUtils.copyProperties(page, attrVOIPage);
        attrVOIPage.setRecords(respVOList);
        return new PageUtils(attrVOIPage);
    }

    /**
     * 查询属性
     *
     * @param attrId
     * @return
     */
    @Override
    public AttrVO queryDetail(Long attrId) {
        PmsAttrEntity attrEntity = baseMapper.selectById(attrId);
        AttrVO attrVO = new AttrVO();
        if (attrEntity != null) {
            BeanUtils.copyProperties(attrEntity, attrVO);
            // 查询属性关联的分类路径
            Long[] categoryPath = categoryService.getCategoryPath(attrEntity.getCatelogId());
            attrVO.setCatelogPath(categoryPath);
            // 查询属性的所属分组
            PmsAttrAttrgroupRelationEntity relationEntity = attrAttrgroupRelationDao
                    .selectOne(
                            new LambdaQueryWrapper<PmsAttrAttrgroupRelationEntity>()
                                    .eq(PmsAttrAttrgroupRelationEntity::getAttrId, attrEntity.getAttrId())
                    );
            if (relationEntity != null) {
                attrVO.setAttrGroupId(relationEntity.getAttrGroupId());
            }
        }
        return attrVO;
    }

    /**
     * 更新属性
     *
     * @param attrVO
     */
    @Transactional
    @Override
    public void updateDetail(AttrVO attrVO) {
        // 修改属性&属性分组关系
        if (ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode().equals(attrVO.getAttrType())) {
            LambdaQueryWrapper<PmsAttrAttrgroupRelationEntity> queryWrapper = new LambdaQueryWrapper<PmsAttrAttrgroupRelationEntity>()
                    .eq(PmsAttrAttrgroupRelationEntity::getAttrId, attrVO.getAttrId());

            Long count = attrAttrgroupRelationDao.selectCount(queryWrapper);

            PmsAttrEntity oldAttrEntity = baseMapper.selectById(attrVO.getAttrId());
            if (oldAttrEntity != null) {
                PmsAttrAttrgroupRelationEntity relationEntity = new PmsAttrAttrgroupRelationEntity();
                relationEntity.setAttrGroupId(attrVO.getAttrGroupId());
                relationEntity.setAttrId(attrVO.getAttrId());
                // // 判断是否修改了分类
                if (oldAttrEntity.getCatelogId().equals(attrVO.getAttrId())) {//没有修改分类
                    if (count != 0) {//原来就关联了分组
                        attrAttrgroupRelationDao.update(relationEntity, queryWrapper);
                    } else {
                        attrAttrgroupRelationDao.insert(relationEntity);
                    }
                } else {// 修改了分类
                    // 删除原来的分组关系
                    attrAttrgroupRelationDao.delete(queryWrapper);
                    // 新增分组关系
                    attrAttrgroupRelationDao.insert(relationEntity);
                }
            }
        }


        // 更新属性信息
        PmsAttrEntity newAttrEntity = new PmsAttrEntity();
        BeanUtils.copyProperties(attrVO, newAttrEntity);
        baseMapper.updateById(newAttrEntity);
    }

}
